﻿using Gameplay.PVE;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using NpcFramework;
using System;
using System.Collections.Generic;
using com.youzu.warh.protocol;
using FluffyUnderware.Curvy;
using UnityEngine;
using XLua;
using Yoozoo.Gameplay.Liberty;
using Yoozoo.Gameplay.Liberty.AI;
using Random = UnityEngine.Random;

namespace Yoozoo.Gameplay.SceneSeparate
{
    [System.Serializable]
    public class SceneNpcBirthPoint : ISceneObject
    {
        [SerializeField]
        private SceneObjType m_sceneType;

        [SerializeField] 
        private Vector3 m_position;
        [SerializeField] 
        private Bounds m_bounds;
        
        [SerializeField] 
        private NpcBrithPointData m_npcBrithPointData;
        [SerializeField] 
        public int pointIndex;

        [NonSerialized]
        private List<int> npcIds;
        [NonSerialized]
        private GameObject triggerObj;
        [SerializeField]
        public string pointName;

        private int uId;

        private int _npcType = -1;
        public int npcType
        {
            get
            {
                if (_npcType > 0)
                {
                    return _npcType;
                }

                if (m_npcBrithPointData.RootName.Contains("static"))
                {
                    _npcType = 1;
                }
                else if (m_npcBrithPointData.RootName.Contains("dynamic"))
                {
                    _npcType = 2;
                }
                else if (m_npcBrithPointData.RootName.Contains("car"))
                {
                    _npcType = 3;
                }
                // PbNpcDataConfig cfg = LibertyConfigManager.GetInstance().GetNpcDataConfig(m_npcBrithPointData.RootName);
                // if (cfg != null)
                // {
                //     _npcType = cfg.Type;
                //     return _npcType;
                // }
                
                return -1;
            }
        }

        public Vector3 Position
        {
            get
            {
                return m_position;
            }
        }

        public NpcBrithPointData BrithPointData
        {
            get { return m_npcBrithPointData; }
        }
        public SceneObjType SceneObjType
        {
            get { return m_sceneType; }
        }

        public SceneNpcBirthPoint(Bounds bounds, 
            SceneObjType sceneObjType, 
            Vector3 position, 
            NpcBrithPointData npcBrithPointData,
            int index,string name)
        {
            Bounds = bounds;
            m_sceneType = sceneObjType;
            m_position = position;
            m_npcBrithPointData = npcBrithPointData;
            pointIndex = index;
            m_npcBrithPointData.Index = index;
        }

        public Bounds Bounds
        {
            get
            {
                return m_bounds;
            }
            set { m_bounds = value; }
        }

        private int _carUniqueId;
        
        public bool OnShow(Transform parent, Action<GameObject> callBack = null)
        {
            // 此为之前的逻辑，目前替换为，主角一定范围内加载
            //if (Random.Range(0, 100) < m_npcBrithPointData.NpcBornProbability)
            //{
            //    if (npcIds == null)
            //    {
            //        npcIds = new List<int>(3);
            //    }
            //    CreateNpcByPointType(m_npcBrithPointData);
            //}

            //PbNpcDataConfig cfg = LibertyConfigManager.GetInstance().GetNpcDataConfig(m_npcBrithPointData.RootName);
            //if (cfg != null)
            //{
            string[] nameSplit = m_npcBrithPointData.RootName.Split("_");
            if (nameSplit == null || nameSplit.Length < 2)
            {
                return false;
            }
                uId = int.Parse(nameSplit[1]);
                int npcModelId = -1;//cfg.Npc_Model_Id;
                int graphId = 1001;//cfg.Graph_Id;
                string aniState = "";//cfg.Anim_State;
                int splineId = 0;//cfg.Spline_Id;
                int splineIndex = 0;
                if (nameSplit.Length > 3)
                {
                    splineId = int.Parse(nameSplit[2]);
                    splineIndex = int.Parse(nameSplit[3]);
                }
                

                AIBirthData birthData = new AIBirthData();
                birthData.uniqueId = uId;
                birthData.position = m_npcBrithPointData.Position;
                birthData.forward = m_npcBrithPointData.Forward;
                birthData.lookAtType = 1;//cfg.Look_At;
                birthData.modelResId = npcModelId;

                if (npcModelId == -1)
                {
                    birthData.randomModel = true;
                }
                // 动态npc
                if (npcType == 2)
                {
                    birthData.isStatic = false;
                    birthData.isFindNearlyPath = true;
                    LibertyAIUtils.AIManager.DynamicNpcManager.AddDynamicNpc(birthData, graphId);
                }
                else if (npcType == 1)
                {
                    birthData.isStatic = true;
                    birthData.animState = aniState;
                    birthData.maxSpeed = 0;
                    LibertyAIUtils.AIManager.AddNpc(birthData, graphId);
                }
                else if (npcType == 3)
                {
                    // AI车辆
                    CarBirthData birthCarData = new CarBirthData();
                    birthCarData.position = m_npcBrithPointData.Position;
                    birthCarData.forward = m_npcBrithPointData.Forward;
                    birthCarData.random = true;
                    birthCarData.pathId = splineId;
                    birthCarData.pathPointIndex = splineIndex;
                    birthCarData.uniqueId = uId;
                    birthCarData.customPos = true;
                    birthCarData.checkCenter = m_npcBrithPointData.checkCenter;
                    birthCarData.checkSize = m_npcBrithPointData.checkSize;
                    birthCarData.maxSpeed = 12.5f;
                    birthCarData.deceleration = 38f;
                    LibertyAIUtils.AIManager.CarBirthManager.AddCarBirthData(birthCarData);
                    return true; 
                }
                else if (npcType == 4)
                {
                    // 静态车辆
                    CarBirthData birthCarData = new CarBirthData();
                    birthCarData.position = m_npcBrithPointData.Position;
                    birthCarData.forward = m_npcBrithPointData.Forward;
                    birthCarData.random = npcModelId == -1;
                    birthCarData.carModelId = npcModelId;
                    birthCarData.checkCenter = m_npcBrithPointData.checkCenter;
                    birthCarData.checkSize = m_npcBrithPointData.checkSize;

                    LibertyAIUtils.AIManager.CarBirthManager.AddCarPure(birthCarData);
                    _carUniqueId = birthCarData.uniqueId;
                    CarEntity carEntity = LibertyAIUtils.AIManager.CarBirthManager.GetCarEntity(_carUniqueId);
                    if (carEntity != null)
                    {
                        carEntity.data.carStyle = CarStyle.Static;
                    }
                }

                return true;
            //}
            //return false;
        }

        // protected void GetInterpolatedSourcePosition(CurvySpline spline, float tf, out Vector3 interpolatedPosition, out Vector3 tangent, out Vector3 up)
        // {
        //     Transform splineTransform = spline.transform;
        //
        //     float localF;
        //     CurvySplineSegment currentSegment = spline.TFToSegment(tf, out localF);
        //     if (ReferenceEquals(currentSegment, null) == false)
        //     {
        //         currentSegment.InterpolateAndGetTangent(localF, out interpolatedPosition, out tangent);
        //         up = currentSegment.GetOrientationUpFast(localF);
        //     }
        //
        //     else
        //     {
        //         interpolatedPosition = Vector3.zero;
        //         tangent = Vector3.zero;
        //         up = Vector3.zero;
        //     }
        //
        //     interpolatedPosition = splineTransform.TransformPoint(interpolatedPosition);
        //     tangent = splineTransform.TransformDirection(tangent);
        //     up = splineTransform.TransformDirection(up);
        // }
        
        private void CreateNpcByPointType(NpcBrithPointData pointData)
        {
            if (pointData.ObjType == SceneObjType.BirthPointParent)
            {
                if (pointData.ChildBirthPoint != null && pointData.ChildBirthPoint.Length > 0)
                {
                    int randomIndex = Random.Range(0, pointData.ChildBirthPoint.Length);
                    var childPointDataIndex = pointData.ChildBirthPoint[randomIndex];
                    var childPointData = PveSceneResourceManager.sceneSeparateMgr.GetNpcPointData(childPointDataIndex);
                    CreateNpcByPointType(childPointData);
                }
            }
            else if (pointData.ObjType == SceneObjType.NpcGroup)
            {
                // int groupId = pointData.GroupId;
                // var info = PveSceneResourceManager.sceneSeparateMgr.GetNpcGroupInfo(groupId);
                // int randomNum = info.npcPointData.Count;
                // int[] nonIndexArray = null;
                // if (randomNum < PveResourceManager.maxPeopleResCount)
                // {
                //      nonIndexArray = PveUtils.UseHasTableToNonRepeatedRandom(randomNum, 0, PveResourceManager.maxPeopleResCount);
                //     
                // }
                //
                // if (NFMgr.NpcBirthManager.CurrentTotalCount +  info.npcPointData.Count > NFConstValue.MaxNpcNum)
                // {
                //     return;
                // }
                //
                // for (int i = 0; i < info.npcPointData.Count; i++)
                // {
                //     var groupPoint = info.npcPointData[i];
                //     //NFMgr.NpcBirthManager.BindPointWithNpcId(pointData.Index, npcId);
                //     int npcId = NFMgr.NpcSelfAddId;
                //     npcIds.Add(npcId);
                //     var rotation = Quaternion.FromToRotation(Vector3.forward, groupPoint.Forward);//npc的朝向角度
                //     var pointDataRotation = Quaternion.FromToRotation(Vector3.forward, pointData.Forward);//组节点的角度
                //     var parentRotation = Quaternion.FromToRotation(Vector3.forward, m_npcBrithPointData.Forward);//父节点的角度
                //     var finalForward = rotation * parentRotation * Vector3.forward;//npc最终的朝向
                //
                //     Vector3 groupChildRoteLocoPosition = pointDataRotation * groupPoint.Position;//组子npc相对组原点的位置
                //     
                //     var generateInfo = new GenerateInfo(npcId, pointData.Position + groupChildRoteLocoPosition, finalForward,
                //         RPGTreeBehaviors.Instance.GetAIBehaviour(groupPoint.BTreePath), false, 0, false, true)
                //     {
                //         animName = groupPoint.PlayAnimName,
                //         npcModelId = groupPoint.ModelId,
                //         isRandomModel = groupPoint.IsRandom
                //     };
                //
                //     if (nonIndexArray != null && generateInfo.isRandomModel)
                //     {
                //         generateInfo.npcModelId = nonIndexArray[i];
                //         generateInfo.isRandomModel = false;
                //     }
                //     GeneratePointNpc(generateInfo);
                // }
            }
            else if (pointData.ObjType == SceneObjType.Event)
            {
                // if (triggerObj !=null)
                // {
                //     GameObject.DestroyImmediate(triggerObj);
                // }
                // triggerObj = new GameObject("trigger");
                // var collider = triggerObj.AddComponent<BoxCollider>();
                // collider.size = m_npcBrithPointData.TriggerSize;
                // collider.isTrigger = true;
                // var pointEventTrigger = triggerObj.AddComponent<NpcPointEventTrigger>();
                // pointEventTrigger.EventName = m_npcBrithPointData.EventName;
                // if (m_npcBrithPointData.IsNpcEvent)
                // {
                //     if (m_npcBrithPointData.ChildBirthPoint != null && m_npcBrithPointData.ChildBirthPoint.Length > 0)
                //     {
                //         for (int i = 0; i < m_npcBrithPointData.ChildBirthPoint.Length; i++)
                //         {
                //             int index = m_npcBrithPointData.ChildBirthPoint[i];
                //             var childPointData = PveSceneResourceManager.sceneSeparateMgr.GetNpcPointData(index);
                //             CreateNpcByPointType(childPointData);
                //         }
                //     }
                //     NFMgr.NpcDialogManager.RegisterDialog(pointIndex, npcIds);
                //     NFMgr.NpcDialogManager.UpdateDialogInfo(pointIndex, m_npcBrithPointData.EventId);
                // }
                // pointEventTrigger.IsNpcEvent = m_npcBrithPointData.IsNpcEvent;
                // pointEventTrigger.TriggerPosition = m_npcBrithPointData.TriggerPosition;
                // pointEventTrigger.TriggerForward = m_npcBrithPointData.TriggerForward;
                // pointEventTrigger.PointIndex = pointIndex;
                //
                // triggerObj.transform.position = m_npcBrithPointData.Position;
            }
            else
            {
                // int npcId = NFMgr.NpcSelfAddId;
                // var generateInfo = new GenerateInfo(npcId, pointData);
                // if (!generateInfo.isHostingDelete)
                // {
                //     npcIds.Add(npcId);
                // }
                // GeneratePointNpc(generateInfo);
            }
        }


        // public void GeneratePointNpc(GenerateInfo generateInfo)
        // {
        //     NFMgr.NpcBirthManager.GeneratePointNpc(generateInfo);
        // }


        public void OnHide()
        {
            // if (npcType == 1)
            // {
            //     LibertyAIUtils.AIManager.RemoveNpc(uId);
            // }
            // 动态Npc和车辆不由场景检测器负责移除，而是在生成管理器中自行管理
            // else if (npcType == 2)
            // {
            //     //LibertyAIUtils.AIManager.DynamicNpcManager.RemoveDynamicNpc(uId);
            // }
            // else
            if (npcType == 3)
            {
                LibertyAIUtils.AIManager.CarBirthManager.RemoveCarBirthData(uId);
            }
            else if (npcType == 4)
            {
                if (_carUniqueId > 0)
                {
                    CarEntity carEntity = LibertyAIUtils.AIManager.CarBirthManager.GetCarEntity(_carUniqueId);
                    if (carEntity!=null)
                    {
                        if ((carEntity.data.carStatus & CarStatus.PlayerControl) == 0) // 玩家控制的时候不销毁
                        {
                            if (carEntity.data.carStyle == CarStyle.Static) // 其它状态时不销毁
                            {
                                LibertyAIUtils.AIManager.CarBirthManager.RemoveCar(_carUniqueId);
                            }
                        }
                    }
                }
            }
        }
		
		public void AddLightmapIndices()
        {
        }

        public void RemoveLightmapIndices()
        {
        }

        public void OnCrash()
        {
            
        }

        public bool IsHide { get; set; }
    }
}
